import logging
from voice_assistant.my_state import app_state
from voice_assistant.com_utils import play_notification_sound
from voice_assistant.config_manager import config_manager

def contains_wake_word(text):
    """检查文本中是否包含任一唤醒词"""
    if not text:
        return False
    
    # 规范化文本
    text = text.lower().strip()
    
    wake_words = config_manager.get("wake_words")
    return any([w in text for w in wake_words])
    # 下面的代码用于精确匹配检测，不兼容中文或包含中文的唤醒词
    #
    
    # 精确匹配检查
    # for wake in WAKE_WORDS:
    #     wake_lower = wake.lower()
    #     # 完全匹配
    #     if wake_lower == text:
    #         return True
    #     # 包含匹配（允许唤醒词前后有其他内容）
    #     if wake_lower in text:
    #         # 检查唤醒词是否作为完整词出现（前后是空格或标点）
    #         word_boundaries = [' ', '.', ',', '!', '?', ';', ':', '', '\t', '']
    #         wake_start = text.find(wake_lower)
    #         wake_end = wake_start + len(wake_lower)
            
    #         # 检查唤醒词前面是否是词边界或文本开头
    #         before_ok = (wake_start == 0) or (text[wake_start-1] in word_boundaries)
            
    #         # 检查唤醒词后面是否是词边界或文本结尾
    #         after_ok = (wake_end == len(text)) or (text[wake_end] in word_boundaries)
            
    #         if before_ok and after_ok:
    #             return True
    
    # return False

def handle_wake_word_detection(text):
    """处理唤醒词检测"""
    if contains_wake_word(text):
        logger = logging.getLogger("wake_word")
        logger.info("检测到唤醒词，触发唤醒")
        app_state.waiting_for_wake = False
        app_state.silence_counter = 0
        app_state.is_recording = True
        play_notification_sound()
        return True
    return False